/**
 * Author：LSP
 * Date：2020-11-30
 */

//================================================
// 文件
const fm = FileManager.local()
//================================================

if (!config.runsInWidget) {
    // 运行弹窗检查
    let message = '检查弹窗'
    let options = ['预览脚本', "同步脚本"]
    const synchronousIndex = 1
    let cancelText = '取消'
    let response = await generateListAlert(message, options, cancelText)
    let selectIndex = response.selectIndex
    if (selectIndex == synchronousIndex) {
        await updateScriptableAlert()
    } else {
        await runWidget()
    }
} else {
    // 直接运行脚本
    await runWidget()
}


/**
 * 更新脚本弹窗
 */
async function updateScriptableAlert() {
    // 脚本更新替换
    const js_url = 'https://gitee.com/enjoyee/scriptable/raw/master/Test.js'
    const req = new Request(js_url)
    const codeString = await req.loadString()
    fm.writeString(module.filename, codeString)

    // 完成
    Script.complete()
}

/**
 * 运行脚本
 */
async function runWidget() {
    const widget = new ListWidget()
    widget.setPadding(0, 0, 0, 0)
    let stack = widget.addStack()
    stack.layoutVertically()
    stack.backgroundColor = new Color('ff0000')

    let img_url1 = "http://photo.tuchong.com/2976763/l/351132268.webp" // 600x400
    const req1 = new Request(img_url1)
    let img1 = await req1.loadImage()
    let stack1 = stack.addStack()
    stack1.layoutHorizontally()
    stack1.size = new Size(50, 100)
    stack1.addImage(img1)
    

    let img_url2 = "http://photo.tuchong.com/2976763/l/405003756.webp" // 600x400
    const req2 = new Request(img_url2)
    let img2 = await req2.loadImage()
    let stack2 = stack.addStack()
    stack2.layoutHorizontally()
    stack2.size = new Size(50, 100)
    stack2.addImage(img2)
    

    // let img_url2 = "http://photo.tuchong.com/2976763/l/405003756.webp" // 600x900
    // const req2 = new Request(img_url2)
    // let img2 = await req2.loadImage()
    // let stack2 = stack.addStack()
    // stack2.layoutHorizontally()
    // let widgetImg2 = stack2.addImage(img2)
    // log(`图片尺寸2：${widgetImg2.image.size.width}, ${widgetImg2.image.size.height}`)
    // stack2.addImage(img2)
    // stack2.addImage(img2)
    // stack2.addImage(img2)
    // stack2.addImage(img2)
    // stack2.addImage(img2)

    // 预览大尺寸组件 1035*987*465
    widget.presentMedium()

    Script.setWidget(widget)
    Script.complete()
    ////////////////////////////////////////
}


//================================================


/**
 * 列表形弹窗
 * @param {信息} message 
 * @param {选项} options 
 * @param {取消文字} cancelText 
 */
async function generateListAlert(message, options, cancelText) {
    const alert = new Alert()
    alert.message = message

    for (const option of options) {
        alert.addAction(option)
    }

    alert.addCancelAction(cancelText)

    let select_index = await alert.present()

    return {
        selectIndex: select_index
    }
}

//==================================================================//


